package org.itboys.admin.service.lasted;

import org.apache.commons.lang3.StringUtils;
import org.itboys.admin.dto.lasted.SundayUploadDto;
import org.itboys.admin.entity.lasted.SundayUpload;
import org.itboys.admin.entity.lasted.SundayUpload;
import org.itboys.commons.utils.io.FileUtils;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.framework.resource.ResourceHolder;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseMongoService;
import org.itboys.param.PageResult;
import org.itboys.param.ParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 包名：com.hz.sunday.tianjie.entity.mysql.product
 * 作者 : 江雄
 * Email: empty90911@126.com
 * 时间：2016年3月10日 下午2:52:46
 * 描述: 圣代_文件上传_service。含图片压缩功能
 *
 */


@Service
public class SundayUploadService extends BaseMongoService<SundayUpload> {
	public static final double compress_image_rate=1.50;//图片压缩比。建议1.5倍长宽压缩
	public static final int compress_image_size=1048576;//图片压缩线。单位byte。当前是1MB
	@Resource(name = "adminDS")
	private MongoDataSource financeDataSource;

	protected Class<SundayUpload> getEntityClass() {

		return SundayUpload.class;
	}
	@Override
	protected MongoDataSource getMongoDataSource() {
		return financeDataSource;
	}



	//上传文件名称
	public static String UPLOAD_FILE_OLD_NAME="oldName";
	//上传文件半路径
	public static String UPLOAD_HALF_PATH="halfPath";
	//上传文件全路径
	public static String UPLOAD_FULL_PATH="fullPath";
	//上传文件类型
	public static String UPLOAD_FILE_TYPE="type";
	//上传文件大小
	public static String UPLOAD_FILE_SIZE="size";

	@Autowired
	private ResourceHolder resourceHolder;

    /**
     * 删除文件
	 * @param filePath
     * @return
     */
	public boolean deleteFile(String filePath){

			filePath =resourceHolder.getStringValue("fileUploadPath")+filePath;

			File file = new File(filePath);
			boolean flag = false;
			if(file.isFile() && file.exists()){
				//如果文件被系统占用，可能会导致删除失败。强制清空系统缓存
				System.gc();
				file.delete();
				flag= true;
			}else{
				flag=false;
			}

		return flag;
	}


	/**
	 *上传单个文件
	 * @param file 文件流
	 * @return
	 * @throws IOException
	 */
	public  Map<String,String> uploadSingle(MultipartFile file) throws IOException{
		Map<String,String> map = new HashMap<String, String>();
		map.put(UPLOAD_FILE_OLD_NAME, "");
		map.put(UPLOAD_HALF_PATH, "");
		map.put(UPLOAD_FULL_PATH, "");
		map.put(UPLOAD_FILE_TYPE,"");
		map.put(UPLOAD_FILE_SIZE,"");
		String imgRoot = resourceHolder.getStringValue("imgRoot");
		if(file!=null&&!file.isEmpty()){
			//保存上传文件
			String savePath =resourceHolder.getStringValue("fileUploadPath");
			String oldName = file.getOriginalFilename();
			String filePath = FileUtils.saveFile(file.getInputStream(),
					savePath,
					oldName, file.getContentType());
			//----------------2017年5月8日，压缩图片----------------
			filePath=compressImage(file, filePath);

			map.put(UPLOAD_FILE_OLD_NAME, file.getOriginalFilename());
			map.put(UPLOAD_HALF_PATH, filePath);
			//System.out.println("UPLOAD_HALF_PATH"+filePath);
			map.put(UPLOAD_FULL_PATH,imgRoot+filePath);
			map.put(UPLOAD_FILE_TYPE,file.getContentType());
			map.put(UPLOAD_FILE_SIZE,String.valueOf(file.getSize()/1024));
			//file.getContentType()
			return map;
		}


		 return map;
	}

	/**
	 * 上传文件，顺便保存记录。主要是后台使用
	 * @param file
	 * @param classId
	 * @param className
	 * @param remark
	 * @return
	 * @throws IOException
	 */
	public  Map<String,String>  uploadSingleWithRecord(MultipartFile file,Long classId,String className,String remark) {
		Map<String,String> result = new HashMap<String,String>();
		try {
			 result=uploadSingle(file);
		}catch (Exception e){
			e.printStackTrace();
		}
		super.save(new SundayUpload(classId,className,result.get(UPLOAD_HALF_PATH),remark,result.get(UPLOAD_FILE_TYPE),result.get(UPLOAD_FILE_SIZE)));
		return result;
	}
	/**
	 * 上传多个文件
	 * @param files
	 * @return
	 * @throws IOException
	 */
	/**
	 * 上传多个文件
	 * @param files
	 * @return
	 * @throws IOException
	 */
	public  List<Map<String,String>> uploadMulti(MultipartFile[] files) throws IOException{
		List<Map<String,String>> result = new ArrayList<Map<String,String>>();
		if(files!=null&&files.length>0){

			String imgRoot = resourceHolder.getStringValue("imgRoot");

		for(MultipartFile file:files){
			Map<String,String> map = new HashMap<String, String>();
			map.put(UPLOAD_FILE_OLD_NAME, "");
			map.put(UPLOAD_HALF_PATH, "");
			map.put(UPLOAD_FULL_PATH, "");
			map.put(UPLOAD_FILE_TYPE,"");
			map.put(UPLOAD_FILE_SIZE,"");
					if(file!=null&&!file.isEmpty()){
						String savePath =resourceHolder.getStringValue("fileUploadPath");
						String oldName = file.getOriginalFilename();
						String filePath = FileUtils.saveFile(file.getInputStream(),
								savePath,
								oldName, file.getContentType());
						//----------------2017年5月8日，压缩图片----------------
						filePath=compressImage(file, filePath);

						map.put(UPLOAD_FILE_OLD_NAME, file.getOriginalFilename());
						map.put(UPLOAD_HALF_PATH, filePath);
						map.put(UPLOAD_FULL_PATH, imgRoot+filePath);
						map.put(UPLOAD_FILE_TYPE,file.getContentType());
						map.put(UPLOAD_FILE_SIZE,String.valueOf(file.getSize()/1024));
						result.add(map);

					}

			}



		}
		return result;
	}
	/**
	 * 上传文件，顺便保存记录。主要是后台使用
	 * @param files
	 * @param classId
	 * @param className
	 * @param reamrk
	 * @return
	 * @throws IOException
	 */
	public  List<Map<String,String>> uploadMultiWithRecord(MultipartFile[] files,Long classId,String className,String reamrk) {
		List<Map<String,String>> result = new ArrayList<Map<String,String>>();
		try {
			result=uploadMulti(files);
		}catch (Exception e){
			e.printStackTrace();
		}
		//logger.info("result-------"+result.size());
		List<SundayUpload> uploadFiles = new ArrayList<SundayUpload>();

		for(Map<String,String> r:result){
			if(StringUtils.isNotEmpty(r.get(UPLOAD_HALF_PATH))){
				SundayUpload uploadFile=new SundayUpload(classId,className,r.get(UPLOAD_HALF_PATH),reamrk,r.get(UPLOAD_FILE_TYPE),r.get(UPLOAD_FILE_SIZE));
				uploadFiles.add(uploadFile);
			}
		}
		if(ListUtil.isNotNull(uploadFiles)){
			super.batchSave(uploadFiles);
		}
		return result;
	}


	/**
	 * 获取上传的附件。不分页
	 * @param outClassName。类名
	 * @param outClassId。类ID
	 * @return
	 */
	public  List<SundayUploadDto> selectNoPage(Long outClassId, String outClassName) {
		List<Map<String,Object>> result = new ArrayList<Map<String,Object>>();
		Map<String,Object> param = new HashMap<String, Object>();
		param.put("isDeleted",0);
		if(LongUtil.isNotZreo(outClassId)){
			param.put("outClassId",outClassId);
		}
		if(StringUtils.isNotBlank(outClassName)){
			param.put("outClassName",outClassName);
		}

		return packageDtoMuilt(super.list(param));
	}
	/**
	 * 获取上传的附件。分页
	 * @param outClassName。类名
	 * @param outClassId。类ID
	 * @return
	 */
	public PageResult<SundayUploadDto> select(HttpServletRequest request, Long outClassId, String outClassName) {
		//List<Map<String,Object>> result = new ArrayList<Map<String,Object>>();
		Map<String,Object> param = new HashMap<String, Object>();
		param.put("isDeleted",0);
		if(LongUtil.isNotZreo(outClassId)){
			param.put("outClassId",outClassId);
		}
		if(StringUtils.isNotBlank(outClassName)){
			param.put("outClassName",outClassName);
		}
		Map<String,String> containsparam = ParamUtil.packageMongoVagueParam(request, "remark");

		PageResult<SundayUpload> result = super.containpageQuery(request,containsparam,param);
		return new PageResult<SundayUploadDto>(packageDtoMuilt(result.getData()),result.getTotal());

	//	return super.containpageQuery(containsparam,param);
	}
	/**
	 * 组装DTO
	 * @return
	 */
	public SundayUploadDto packageDtoSingle(SundayUpload file){
		//String imageboot =;
		return 	new SundayUploadDto(
				file.getId(),file.getCreateTime(), file.getCreateDate(), file.getIsDeleted(),
				StringUtils.isNotEmpty(file.getSavePath())?resourceHolder.getStringValue("imgRoot")+file.getSavePath():null,
				file.getRemark(),file.getType(),file.getSize());
	}
	public List<SundayUploadDto> packageDtoMuilt(List<SundayUpload> files){
		List<SundayUploadDto> dtos = new ArrayList<>();
		Map<String,Object> param =new HashMap<String, Object>();
		for(SundayUpload file:files){
			dtos.add(packageDtoSingle(file));
		}
		return dtos;
	}
	public SundayUploadDto findOne(Long id, Long classId, String className){
		if(LongUtil.isNotZreo(id)){
			return packageDtoSingle(super.getById(id));
		}else{
			SundayUploadDto dto = new SundayUploadDto(0,classId,className);
			return dto ;
		}
	}

	/**
	 * 压缩图片。
	 * @param file。文件
	 * @param oldImageHalfPath 。已经保存的旧文件半链接地址
	 * @return
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	public  String compressImage(MultipartFile file,String oldImageHalfPath) throws FileNotFoundException, IOException{
		System.out.println("----------图片压缩准备。原始大小："+file.getSize()+"kb--------------------");
		//如果上传文件是图片，且大小超过1m，就开始压缩
		//文件后缀名
		String oldFileSuffix=oldImageHalfPath.substring(oldImageHalfPath.indexOf(".")+1,oldImageHalfPath.length());
		System.out.println("----------图片压缩准备。旧路径，后缀名称："+oldFileSuffix+"--------------------");
		//没有后缀名的文件名
		String oldFileNameNoSuffix=oldImageHalfPath.substring(0,oldImageHalfPath.indexOf("."));
		System.out.println("---------图片压缩准备。旧路径，无后缀名称："+oldFileNameNoSuffix+"--------------------");
		if(file==null||
				StringUtils.isEmpty(file.getContentType())||
				(!oldFileSuffix.equalsIgnoreCase("jpg")&&
								!oldFileSuffix.equalsIgnoreCase("png")
				)||
				file.getSize()<compress_image_size){
			return oldImageHalfPath;

		}
		System.out.println("----------图片压缩开始。原始大小："+file.getSize()+"kb--------------------");

		Image srcImg  = ImageIO.read(new FileInputStream(resourceHolder.getStringValue("fileUploadPath")+oldImageHalfPath) );//取源图

		String widthStr = String.valueOf(Double.valueOf(srcImg.getWidth(null))/compress_image_rate);
		widthStr=widthStr.substring(0,widthStr.indexOf("."));
		String heightStr = String.valueOf(Double.valueOf(srcImg.getHeight(null))/compress_image_rate);
		heightStr=heightStr.substring(0,heightStr.indexOf("."));

		//缩减压缩图片的长和宽
		int  width  =  Integer.valueOf(widthStr);
		int  height  =  Integer.valueOf(heightStr);

       /* System.out.println("Width: "+srcImg.getWidth(null));// 这几行是调试用
        System.out.println("Height: "+srcImg.getHeight(null));
        System.out.println("Width2: "+width);
        System.out.println("Height2: "+height);*/
		Image smallImg =srcImg.getScaledInstance(width, height, Image.SCALE_SMOOTH);//
		BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);

		//再创建一个Graphics变量，用来画出来要保持的图片，及上面传递过来的Image变量
		Graphics g = bi.getGraphics();
		// try {
		g.drawImage(smallImg, 0, 0, null);





		//将BufferedImage变量写入文件中。
		String newFileHalfPath=oldFileNameNoSuffix+"-1."+oldFileSuffix;

		//新的文件-
		File newFile =new File(resourceHolder.getStringValue("fileUploadPath")+newFileHalfPath);
		ImageIO.write(bi,oldFileSuffix,newFile);

		System.out.println("----------图片压缩结束.-------------------");
		return newFileHalfPath;
	}
}
